package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Teacher;

public class TeacherDao {
    //创建一个大小为5的老师数组
    private static Teacher[] teachersArray = new Teacher[5];

    static {
        Teacher teacher1 = new Teacher("heima001", "阿拉松", "20", "1999-10-11");
        Teacher teacher2 = new Teacher("heima002", "彭小晏", "21", "1998-10-12");

        teachersArray[0] = teacher1;
        teachersArray[1] = teacher2;
    }

    //查询

    public Teacher[] findAllTeacher() {
        return teachersArray;
    }

    //添加老师对象进库
    public boolean addTeacher(Teacher teacher) {
        //假定已经满了,加不进去,初始一个flag
        boolean flag = false;
        //因此加一个for循环遍历,只要有一个索引位置的元素是空,就可以添加进去
        for (int i = 0; i < teachersArray.length; i++) {
            Teacher teacher1 = teachersArray[i];
            if (teacher1 == null) {
                flag = true;
                teachersArray[i] = teacher;
                break;
            }
        }
        return flag;
    }

    //删除老师对象
    public void deleteTeacher(String id) {
        int index = getIndex(id);

        //用null覆盖该索引位置的元素
        teachersArray[index] = null;
    }

    //获取指定id的索引
    private int getIndex(String id) {
        //判断需要操作的学号在哪个索引位置
        //假定没有
        int index = -1;
        for (int i = 0; i < teachersArray.length; i++) {
            Teacher teacher = teachersArray[i];
            if (teacher != null && teacher.getId().equals(id)) {
                index = i;
                break;
            }
        }
        return index;
    }

    //修改老师对象
    public void updateTeacherId(Teacher teacher, String id) {
        //获取指定id的索引位置
        int index = getIndex(id);
        //修改当前位置元素
        teachersArray[index] = teacher;
    }
}
